package com.truongnha.clienttn.data.sao;

import org.json.JSONArray;
import org.json.JSONObject;

import com.truongnha.clienttn.data.dao.AttendDAO;
import com.truongnha.clienttn.data.dao.CreateDatabase;
import com.truongnha.clienttn.data.servicehelper.utils;

import config.Url;

import android.content.Context;
import android.util.Log;

public class AttendSAO {
	private Context context;
	private String url;

	public AttendSAO(Context context) {
		super();
		this.url = Url.getURLGetAttendanceForStudentAllYear();
		this.context = context;
	}

	public void getDataFromServer() {
		JSONArray jsArray = utils.getJSONArrayByHttpGet(url);
		saveToDatabase(jsArray);
	}

	private void saveToDatabase(JSONArray jsArray) {

		CreateDatabase db = new CreateDatabase(context);
		AttendDAO attendDAO = new AttendDAO(db.open());
		attendDAO.delete();
		try {
			int size = jsArray.length();
			for (int i = 0; i < size; i++) {
				JSONObject js = jsArray.getJSONObject(i);
				attendDAO.insert(js.getString("type"), js.getString("sent"),
						js.getString("time"));
			}
			db.close();
		} catch (Exception e) {
			db.close();
			Log.d("LOG error", " error in save attend " + e.toString());
		}
	}
}
